package cn.edu.zjut.mina.service.impl;

import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import cn.edu.zjut.mina.bean.RoomInfo;
import cn.edu.zjut.mina.bean.StandardFormat;
import cn.edu.zjut.mina.interf.IRoomInfo;
import cn.edu.zjut.mina.protocal.JMessageProtocalRes;
import cn.edu.zjut.mina.protocal.ProtocalRegulation;
import cn.edu.zjut.mina.service.INotificationService;
import cn.edu.zjut.mina.service.IQuitRoomService;
import cn.edu.zjut.mina.util.DateUtils;
import cn.edu.zjut.mina.util.GsonUtils;
import cn.edu.zjut.mina.util.UserSessionMap;
import cn.edu.zjut.mina.util.ResultInfoConstUtils;
@Service("quitRoomService")
public class QuitRoomServiceImpl implements IQuitRoomService{

	/**
	 * 用于存放用户信息的集合
	 */
	private final UserSessionMap userSessionMap = UserSessionMap.getInstance();
	
	@Qualifier("notificationService")
	@Autowired
	private INotificationService notificationService;
	
	public static final int QUITTYPE = 1;
	public static final int APPLYQUITTYPE = 0;
	public static final int ROOMOWNERDISSOLVEROOM = 2;
	
	public JMessageProtocalRes quitRoom(StandardFormat inJson, IoSession session) {
		// TODO Auto-generated method stub
		System.out.println(DateUtils.getTime() + "用户" + session.getAttribute("user") + "提交退房申请");
		JMessageProtocalRes res = new JMessageProtocalRes();
		StandardFormat outJson = new StandardFormat();
		String datas;
		IRoomInfo roomInfo = userSessionMap.get(inJson.roomId);
		if (roomInfo == null) {
			System.out.println(DateUtils.getTime() + "用户" + session.getAttribute("user") + "");
			System.out.println("房间号错误");
			outJson.userId = inJson.userId;
			outJson.resultInfo = "您提交退出的房间不存在";
			outJson.result = false;
		}  else {
			synchronized(roomInfo) {//参考java编程思想 689页
				roomInfo.setActualJoinQuit(roomInfo.getActualJoinQuit() + 1);//已参加退出人数加一
				if (inJson.quit == 1)
					roomInfo.setActualQuit(roomInfo.getActualQuit() + 1);//退出人数加一
				else {
					notificationService.notificationDissolveOrRemainRoom(inJson.roomId, inJson.userId, 0, QUITTYPE);//一票否决
					return null;
				}
				for (int index = 0; index < roomInfo.getActualParticipation(); index++) {
					if (roomInfo.getUserSessions().get(index).user.getUserId().equals(inJson.userId)) {
						roomInfo.getUserSessions().get(index).user.setQuit(inJson.quit);
						break;
					}
				}
				int loseConnection = 0;
				for (int index = 0; index < roomInfo.getActualParticipation(); index++) {
					if (roomInfo.getUserSessions().get(index).user.getLostConnection() != null && roomInfo.getUserSessions().get(index).user.getLostConnection() == 1) {
						loseConnection++;
					}
				}
				//目前是一票否决状态
				if ((roomInfo.getActualJoinQuit() + loseConnection) == roomInfo.getActualParticipation()) {//所有在线的人都投票了
					if (roomInfo.getActualQuit() == roomInfo.getActualJoinQuit()) {//解散房间
						notificationService.notificationDissolveOrRemainRoom(inJson.roomId, inJson.userId, 1, QUITTYPE);
					} else {//保留房间
						notificationService.notificationDissolveOrRemainRoom(inJson.roomId, inJson.userId, 0, QUITTYPE);
					}
				} else {
					notificationService.notificationQuitRoom(inJson.roomId, inJson.userId);
				}
				return null;
			}
		}
			
		
		res.setResultCode(ProtocalRegulation.QUITROOMINITIATIVE);
		datas = GsonUtils.beanToJson(outJson).trim();
		res.setContent(datas);
		return res;
	}
	
	/**
	 * 申请退房
	 * @param inJson
	 * @param session
	 * @return
	 */
	public JMessageProtocalRes applyQuitRoom(StandardFormat inJson, IoSession session) {
		System.out.println("execute --ApplyQuitRoom()-- method.");
		JMessageProtocalRes res = new JMessageProtocalRes();
		StandardFormat outJson = new StandardFormat();
		String datas;
		IRoomInfo roomInfo = userSessionMap.get(inJson.roomId);
		if (roomInfo == null) {
			System.out.println("房间号错误");
			outJson.userId = inJson.userId;
			outJson.resultInfo = "您申请退出的房间不存在";
			outJson.result = false;
		} else {
			synchronized(roomInfo) {
				roomInfo.setActualJoinQuit(roomInfo.getActualJoinQuit() + 1);//已参加退出人数加一
				roomInfo.setActualQuit(roomInfo.getActualQuit() + 1);//退出人数加一
				
				for (int index = 0; index < roomInfo.getActualParticipation(); index++) {
					if (roomInfo.getUserSessions().get(index).user.getUserId().equals(inJson.userId)) {
						roomInfo.getUserSessions().get(index).user.setQuit(1);
						break;
					}
				}
				int loseConnection = 0;
				for (int index = 0; index < roomInfo.getActualParticipation(); index++) {
					if (roomInfo.getUserSessions().get(index).user.getLostConnection() != null && roomInfo.getUserSessions().get(index).user.getLostConnection() == 1) {
						loseConnection++;
					}
				}
				//目前是一票否决状态
				if ((roomInfo.getActualJoinQuit() + loseConnection) == roomInfo.getActualParticipation()) {//所有在线的人都投票了
					if (roomInfo.getActualQuit() == roomInfo.getActualJoinQuit()) {//解散房间
						notificationService.notificationDissolveOrRemainRoom(inJson.roomId, inJson.userId, 1, APPLYQUITTYPE);
					} else {//保留房间
						notificationService.notificationDissolveOrRemainRoom(inJson.roomId, inJson.userId, 0, APPLYQUITTYPE);
					}
				} else {
					notificationService.notificationQuitRoom(inJson.roomId, inJson.userId);
				}
				return null;
			}
		}
		
		
		
		res.setResultCode(ProtocalRegulation.APPLYQUITROOM);
		datas = GsonUtils.beanToJson(outJson).trim();
		res.setContent(datas);
		return res;
	}

	/**
	 * 房主一键解散房间
	 */
	public JMessageProtocalRes constraintQuitRoom(StandardFormat inJson,
			IoSession session) {
		// TODO Auto-generated method stub
		System.out.println("execute --QuitRoom()-- method.");
		JMessageProtocalRes res = new JMessageProtocalRes();
		StandardFormat outJson = new StandardFormat();
		String datas;
		IRoomInfo roomInfo = userSessionMap.get(inJson.roomId);
		if (roomInfo == null) {
			outJson.userId = inJson.userId;
			outJson.resultInfo = ResultInfoConstUtils.QUITROOM_ROOMNULLINFO;
			outJson.result = false;
		}  else {
			notificationService.notificationDissolveOrRemainRoom(inJson.roomId, inJson.userId, 1, ROOMOWNERDISSOLVEROOM);
			return null;
		}
		
		res.setResultCode(ProtocalRegulation.ROOMOWNERDISSOLVEROOMINITIATIVE);
		datas = GsonUtils.beanToJson(outJson).trim();
		res.setContent(datas);
		return res;
	}

}
